package com.microservice.user.controller;

import com.microservice.common.util.MailTestUtil;
import com.microservice.common.util.MailUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 邮件测试控制器
 */
@RestController
@RequestMapping("/test/mail")
@RequiredArgsConstructor
public class MailTestController {
    
    private final MailTestUtil mailTestUtil;
    private final MailUtil mailUtil;
    
    /**
     * 测试邮件连接
     * 访问: http://localhost:8081/test/mail/connection
     */
    @GetMapping("/connection")
    public Map<String, Object> testConnection() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = mailTestUtil.testConnection(
                "smtp.qq.com",
                465,
                "2300941699@qq.com",
                "rpxdfkjwghqjeadb",
                true
            );
            
            result.put("success", success);
            result.put("message", success ? "✅ 邮件服务器连接成功" : "❌ 邮件服务器连接失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "❌ 连接测试异常: " + e.getMessage());
            result.put("error", e.toString());
        }
        
        return result;
    }
    
    /**
     * 发送测试邮件
     * 访问: http://localhost:8081/test/mail/send?to=your@email.com
     */
    @GetMapping("/send")
    public Map<String, Object> sendTestMail(@RequestParam String to) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = mailTestUtil.sendTestMail(
                "smtp.qq.com",
                465,
                "2300941699@qq.com",
                "rpxdfkjwghqjeadb",
                true,
                to
            );
            
            result.put("success", success);
            result.put("to", to);
            result.put("message", success ? "✅ 测试邮件发送成功" : "❌ 测试邮件发送失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "❌ 发送测试异常: " + e.getMessage());
            result.put("error", e.toString());
        }
        
        return result;
    }
    
    /**
     * 使用 MailUtil 发送简单邮件（同步）
     * 访问: http://localhost:8081/test/mail/send-simple?to=your@email.com
     */
    @GetMapping("/send-simple")
    public Map<String, Object> sendSimpleMail(@RequestParam String to) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = mailUtil.sendSimpleMail(
                to,
                "测试邮件 - 简单文本",
                "这是一封测试邮件\n\n如果您收到此邮件，说明邮件功能正常！\n\n发送时间：" + System.currentTimeMillis()
            );
            
            result.put("success", success);
            result.put("to", to);
            result.put("message", success ? "✅ 简单邮件发送成功" : "❌ 简单邮件发送失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "❌ 发送异常: " + e.getMessage());
            result.put("error", e.toString());
        }
        
        return result;
    }
    
    /**
     * 使用 MailUtil 发送 HTML 邮件（异步）
     * 访问: http://localhost:8081/test/mail/send-html?to=your@email.com
     */
    @GetMapping("/send-html")
    public Map<String, Object> sendHtmlMail(@RequestParam String to) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String html = """
                <html>
                <body style="font-family: Arial, sans-serif;">
                    <div style="max-width: 600px; margin: 0 auto; padding: 20px; background-color: #f5f5f5;">
                        <h2 style="color: #4CAF50;">✅ 邮件测试成功</h2>
                        <p>如果您收到这封邮件，说明：</p>
                        <ul>
                            <li>邮件服务器配置正确</li>
                            <li>网络连接正常</li>
                            <li>授权码有效</li>
                        </ul>
                        <hr>
                        <p style="color: #666; font-size: 12px;">
                            发送时间：%s<br>
                            发件人：2300941699@qq.com
                        </p>
                    </div>
                </body>
                </html>
                """.formatted(new java.util.Date());
            
            // 异步发送
            mailUtil.sendHtmlMailAsync(to, "测试邮件 - HTML格式", html);
            
            result.put("success", true);
            result.put("to", to);
            result.put("message", "✅ HTML邮件已提交异步发送队列，请查收邮箱");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "❌ 发送异常: " + e.getMessage());
            result.put("error", e.toString());
        }
        
        return result;
    }
    
    /**
     * 使用 MailUtil 发送模板邮件（异步，带频率限制）
     * 访问: http://localhost:8081/test/mail/send-template?to=your@email.com&userId=123
     */
    @GetMapping("/send-template")
    public Map<String, Object> sendTemplateMail(
            @RequestParam String to,
            @RequestParam(defaultValue = "123") String userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String template = """
                <html>
                <body style="font-family: Arial;">
                    <h2>您好，${username}！</h2>
                    <p>您的验证码是：<strong style="color: red; font-size: 24px;">${code}</strong></p>
                    <p>验证码将在 ${expireTime} 分钟后过期。</p>
                    <p style="color: #999;">如非本人操作，请忽略此邮件。</p>
                </body>
                </html>
                """;
            
            Map<String, String> params = new HashMap<>();
            params.put("username", "测试用户" + userId);
            params.put("code", "888888");
            params.put("expireTime", "5");
            
            // 异步发送，带频率限制（1分钟内同一用户只能发一次）
            mailUtil.sendTemplateMailAsync(userId, to, "测试邮件 - 验证码", template, params);
            
            result.put("success", true);
            result.put("to", to);
            result.put("userId", userId);
            result.put("message", "✅ 模板邮件已提交异步发送队列（带频率限制）");
            result.put("note", "同一用户1分钟内只能向同一收件人发送一次");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "❌ 发送异常: " + e.getMessage());
            result.put("error", e.toString());
        }
        
        return result;
    }
    
    /**
     * 测试 587 端口（STARTTLS）
     * 访问: http://localhost:8081/test/mail/test-587
     */
    @GetMapping("/test-587")
    public Map<String, Object> test587Port() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = mailTestUtil.testConnection(
                "smtp.qq.com",
                587,
                "2300941699@qq.com",
                "rpxdfkjwghqjeadb",
                false  // 587端口使用STARTTLS，不用SSL
            );
            
            result.put("success", success);
            result.put("port", 587);
            result.put("message", success ? "✅ 587端口连接成功（STARTTLS）" : "❌ 587端口连接失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "❌ 连接测试异常: " + e.getMessage());
            result.put("error", e.toString());
        }
        
        return result;
    }
    
    /**
     * 获取所有测试接口
     * 访问: http://localhost:8081/test/mail/help
     */
    @GetMapping("/help")
    public Map<String, Object> help() {
        Map<String, Object> result = new HashMap<>();
        result.put("title", "邮件测试接口列表");
        
        Map<String, String> apis = new HashMap<>();
        apis.put("GET /test/mail/connection", "测试邮件服务器连接（465端口SSL）");
        apis.put("GET /test/mail/test-587", "测试邮件服务器连接（587端口STARTTLS）");
        apis.put("GET /test/mail/send?to=xxx", "使用原生API发送测试邮件");
        apis.put("GET /test/mail/send-simple?to=xxx", "使用MailUtil发送简单文本邮件");
        apis.put("GET /test/mail/send-html?to=xxx", "使用MailUtil发送HTML邮件（异步）");
        apis.put("GET /test/mail/send-template?to=xxx&userId=123", "使用MailUtil发送模板邮件（异步+频率限制）");
        
        result.put("apis", apis);
        result.put("example", "http://localhost:8081/test/mail/send-html?to=wang_haoge0916@163.com");
        
        return result;
    }
}
